import { defineStore } from 'pinia'
import api from '../services/api'
import type { User } from '../types'

interface UserState {
  user: User | null
  isAuthenticated: boolean
  loading: boolean
}

export const useUserStore = defineStore('user', {
  state: (): UserState => ({
    user: null,
    isAuthenticated: false,
    loading: false
  }),
  
  getters: {
    username: (state) => state.user?.username || '',
    isAdmin: (state) => state.user?.role === 'admin'
  },
  
  actions: {
    async fetchUserInfo() {
      try {
        this.loading = true
        const { data } = await api.get<User>('/auth/me')
        this.user = data
        this.isAuthenticated = true
      } catch {
        this.user = null
        this.isAuthenticated = false
      } finally {
        this.loading = false
      }
    },
    
    clearUserInfo() {
      this.user = null
      this.isAuthenticated = false
    }
  }
}) 